🔹Уровень: Advanced 🔹Темы: замыкания (closures), переменные цикла, lambda, отложенное выполнение
📌Условие
Что выведет следующий код?
funcs = []
for i in range(5): funcs.append(lambda: i)
results = [f() for f in funcs] print(results)
❓Вопросы
1. Почему вывод может не соответствовать ожиданиям [0, 1, 2, 3, 4]? 2. Что именно "запоминает" lambda внутри цикла? 3. Как переписать код, чтобы результат был [0, 1, 2, 3, 4]?
🔍Разбор
✅Ожидаемый (неправильный) вывод:
[4, 4, 4, 4, 4]
🔧Почему так происходит
- Все lambda внутри funcsзамыкают одну и ту же переменную `i`. - К моменту выполнения f() переменная i уже равна 4 — и так для всех функций.
⚠️Подвох
lambda: iне захватывает значение, а ссылается на переменную, которая будет изменяться при каждой итерации цикла. В итоге — все lambda ссылаются на одно и то же `i`, которое стало равно 4 к концу цикла.
🧠Решение
Нужно "зафиксировать" значение i, передав его как аргумент по умолчанию в lambda:
for i in range(5): funcs.append(lambda i=i: i)
Теперь результат будет:
[0, 1, 2, 3, 4]
📌 Это один из самых частых подвохов в Python, особенно при использовании лямбда-функций в генераторах и UI-коллбеках.
🔹Уровень: Advanced 🔹Темы: замыкания (closures), переменные цикла, lambda, отложенное выполнение
📌Условие
Что выведет следующий код?
funcs = []
for i in range(5): funcs.append(lambda: i)
results = [f() for f in funcs] print(results)
❓Вопросы
1. Почему вывод может не соответствовать ожиданиям [0, 1, 2, 3, 4]? 2. Что именно "запоминает" lambda внутри цикла? 3. Как переписать код, чтобы результат был [0, 1, 2, 3, 4]?
🔍Разбор
✅Ожидаемый (неправильный) вывод:
[4, 4, 4, 4, 4]
🔧Почему так происходит
- Все lambda внутри funcsзамыкают одну и ту же переменную `i`. - К моменту выполнения f() переменная i уже равна 4 — и так для всех функций.
⚠️Подвох
lambda: iне захватывает значение, а ссылается на переменную, которая будет изменяться при каждой итерации цикла. В итоге — все lambda ссылаются на одно и то же `i`, которое стало равно 4 к концу цикла.
🧠Решение
Нужно "зафиксировать" значение i, передав его как аргумент по умолчанию в lambda:
for i in range(5): funcs.append(lambda i=i: i)
Теперь результат будет:
[0, 1, 2, 3, 4]
📌 Это один из самых частых подвохов в Python, особенно при использовании лямбда-функций в генераторах и UI-коллбеках.
BY Python вопросы с собеседований
Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283
You can’t. What you can do, though, is use WhatsApp’s and Telegram’s web platforms to transfer stickers. It’s easy, but might take a while.Open WhatsApp in your browser, find a sticker you like in a chat, and right-click on it to save it as an image. The file won’t be a picture, though—it’s a webpage and will have a .webp extension. Don’t be scared, this is the way. Repeat this step to save as many stickers as you want.Then, open Telegram in your browser and go into your Saved messages chat. Just as you’d share a file with a friend, click the Share file button on the bottom left of the chat window (it looks like a dog-eared paper), and select the .webp files you downloaded. Click Open and you’ll see your stickers in your Saved messages chat. This is now your sticker depository. To use them, forward them as you would a message from one chat to the other: by clicking or long-pressing on the sticker, and then choosing Forward.
Telegram auto-delete message, expiring invites, and more
elegram is updating its messaging app with options for auto-deleting messages, expiring invite links, and new unlimited groups, the company shared in a blog post. Much like Signal, Telegram received a burst of new users in the confusion over WhatsApp’s privacy policy and now the company is adopting features that were already part of its competitors’ apps, features which offer more security and privacy. Auto-deleting messages were already possible in Telegram’s encrypted Secret Chats, but this new update for iOS and Android adds the option to make messages disappear in any kind of chat. Auto-delete can be enabled inside of chats, and set to delete either 24 hours or seven days after messages are sent. Auto-delete won’t remove every message though; if a message was sent before the feature was turned on, it’ll stick around. Telegram’s competitors have had similar features: WhatsApp introduced a feature in 2020 and Signal has had disappearing messages since at least 2016.